package leetcode.f1t100;

/**
 * 给一串数字, 数字代表可向后跳的步数, 得到最少的步数可跳完整个数组
 * https://leetcode.com/problems/jump-game-ii/
 *
 * @Author lichongxiao
 * @Date 2022/10/21 9:16
 */
public class Q45_JumpGameII {
    public int jump(int[] nums) {
        return jumpdp(nums);
    }

    private int jumpdp(int[] nums) {
        int[] dp = new int[nums.length];
        dp[nums.length - 1] = 0;
        for (int i = nums.length - 2; i >= 0; i--) {
            if (nums[i] <= 0) {
                dp[i] = Integer.MAX_VALUE;
                continue;
            }
            int temp = Integer.MAX_VALUE;
            for (int j = 1; j <= nums[i] && i + j < nums.length; j++) {
                temp = temp > dp[i + j] ? dp[i + j] : temp;
            }
            dp[i] = temp == Integer.MAX_VALUE ? temp : temp + 1;
        }
        return dp[0];
    }

    private int jumpGreedy(int[] nums) {
        int step = 0, curStepEnd = 0, nextStepEnd = 0;
        for (int i = 0; i < nums.length -1; i++) {
            nextStepEnd = i + nums[i] > nextStepEnd ? i + nums[i] : nextStepEnd;
            if (i == curStepEnd) {
                step++;
                if(nextStepEnd > nums.length -1){
                    break;
                }
                curStepEnd = nextStepEnd;
            }
        }
        return step;
    }

    public static void main(String[] args) {
        Q45_JumpGameII bean = new Q45_JumpGameII();
        System.out.println(bean.jump(new int[]{5, 9, 3, 2, 1, 0, 2, 3, 3, 1, 0, 0}));
        System.out.println(bean.jumpGreedy(new int[]{5, 9, 3, 2, 1, 0, 2, 3, 3, 1, 0, 0}));
    }
}
